package com.remoteserver.localclient;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.chchwk.remoteserver.Calculation;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity {

    @InjectView(R.id.et_a)
    EditText etA;
    @InjectView(R.id.et_b)
    EditText etB;
    @InjectView(R.id.btn)
    Button btn;
    @InjectView(R.id.tv)
    TextView tv;

    private Calculation mCalculation;
    private ServiceConnection mServiceConnection;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.inject(this);
        //连接远程服务
        mServiceConnection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName mComponentName, IBinder service) {
                mCalculation = Calculation.Stub.asInterface(service);
            }

            @Override
            public void onServiceDisconnected(ComponentName mComponentName) {
                mCalculation = null;
            }
        };
        //使用意图对象绑定开启服务
        Intent intent = new Intent();
        intent.setAction("com.chchwk.remoteserver.CalculateService");
        //在5.0及以上版本必须要加上这个
        intent.setPackage("com.chchwk.remoteserver");
        bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
    }

    @OnClick(R.id.btn)
    public void onClick() {
        String a = etA.getText().toString();
        String b = etB.getText().toString();
        if (TextUtils.isEmpty(a) && TextUtils.isEmpty(b)) {
            Toast.makeText(MainActivity.this, "您输入的数字不合法", Toast.LENGTH_SHORT).show();
        } else {
            try {//这里只调用了加法
                int addition = mCalculation.addition(Integer.parseInt(a), Integer.parseInt(b));
                tv.setText("调用远程服务加法获取到的计算结果是==" + addition);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }
}

